package com.example.study.common.dataSourceConfig;

import com.alibaba.druid.pool.DruidDataSource;
import com.example.study.common.properties.DruidDataSourceProperties;
import com.example.study.common.properties.DynamicDataSourceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @description：配置多数据源
 * @author: liqiancheng
 * @createTime: 2021/7/26 11:12
 **/
@Configuration
@EnableConfigurationProperties(DynamicDataSourceProperties.class)
public class DynamicDataSourceConfig {

    @Autowired
    private DynamicDataSourceProperties properties;

    /**
     * @author:
     * @createTime: 2020/6/29 15:23
     * @description: 数据源配置加载
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DruidDataSourceProperties dataSourceProperties() {
        return new DruidDataSourceProperties();
    }

    /**
     * @author:
     * @createTime: 2020/6/29 15:23
     * @description: 动态数据源加载
     * @param dataSourceProperties
     * @return
     */
    @Bean
    public DynamicDataSource dynamicDataSource(DruidDataSourceProperties dataSourceProperties) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(getDynamicDataSource());

        //默认数据源
        DruidDataSource defaultDataSource = DynamicDataSourceFactory.buildDruidDataSource(dataSourceProperties);
        dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);
        return dynamicDataSource;
    }

    /**
     * @author:
     * @createTime: 2020/6/29 15:23
     * @description: 动态数据源取出
     * @return
     */
    private Map<Object, Object> getDynamicDataSource(){
        Map<String, DruidDataSourceProperties> dataSourcePropertiesMap = properties.getDatasource();
        Map<Object, Object> targetDataSources = new HashMap<>(dataSourcePropertiesMap.size());
        dataSourcePropertiesMap.forEach((k, v) -> {
            DruidDataSource druidDataSource = DynamicDataSourceFactory.buildDruidDataSource(v);
            targetDataSources.put(k, druidDataSource);
        });

        return targetDataSources;
    }

}
